package com.stylefeng.guns.modular.pay.service.impl;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toSimple;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.Result;
import com.baidu.unbiz.fluentvalidator.jsr303.HibernateSupportedValidator;
import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.AjaxRes;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.JsonUtils;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.core.util.ObjectUtils;
import com.stylefeng.guns.modular.pay.dto.ApiMchRegParams;
import com.stylefeng.guns.modular.pay.dto.ApiPayParams;
import com.stylefeng.guns.modular.pay.exception.ApiException;
import com.stylefeng.guns.modular.pay.exception.BusException;
import com.stylefeng.guns.modular.pay.exception.ResultEnum;
import com.stylefeng.guns.modular.pay.model.BankLimit;
import com.stylefeng.guns.modular.pay.model.Card;
import com.stylefeng.guns.modular.pay.model.MchBus;
import com.stylefeng.guns.modular.pay.model.MchReg;
import com.stylefeng.guns.modular.pay.model.Member;
import com.stylefeng.guns.modular.pay.model.Trans;
import com.stylefeng.guns.modular.pay.payment.jft.common.JftConfigure;
import com.stylefeng.guns.modular.pay.payment.jft.core.AESUtil;
import com.stylefeng.guns.modular.pay.payment.jft.core.MD5Util;
import com.stylefeng.guns.modular.pay.payment.jft.request.QuickPay;
import com.stylefeng.guns.modular.pay.service.IBankLimitService;
import com.stylefeng.guns.modular.pay.service.ICardService;
import com.stylefeng.guns.modular.pay.service.IJftService;
import com.stylefeng.guns.modular.pay.service.IMchBusService;
import com.stylefeng.guns.modular.pay.service.IMchRegService;
import com.stylefeng.guns.modular.pay.service.IMemberService;
import com.stylefeng.guns.modular.pay.service.ITransService;

@Service
public class JftServiceImpl implements IJftService {
    private final static Logger logger = LoggerFactory.getLogger(JftServiceImpl.class);
	private static Validator validator;
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IMchBusService mchBusService;
	@Autowired
	private IMchRegService mchRegService;
	@Autowired
	private IdWorkerService idWorkerService;
	@Autowired
	private ITransService transService;
	@Autowired
	private ICardService cardService;
	@Autowired
	private IBankLimitService bankLimitService;
	
	
	static {
		Locale.setDefault(Locale.ENGLISH); // speicify language
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		validator = factory.getValidator();
	}

	@Override
	public AjaxRes quickPay(ApiPayParams params){
		Result ret = FluentValidator.checkAll()
				.on(params, new HibernateSupportedValidator<ApiPayParams>().setHiberanteValidator(validator))
				.doValidate().result(toSimple());
		if (!ret.isSuccess()) {
			String msg = ret.getErrors().get(0);
			throw new ApiException("validate.error",msg);
		}
		Card card = cardService.selectById(Integer.parseInt(params.getBankId()));
		if(card==null){
			throw new ApiException("empty.card", "card不存在");
		}
		
		Member member = memberService.selectById(Integer.parseInt(params.getMemberId()));
		if(member==null || member.getAuthStatus()!=2){
			throw new ApiException("member.unexist", "商户注册或尚未认证");
		}
		//限额处理
		BankLimit limit = bankLimitService.selectById(card.getBankId());
		if(limit==null){
			throw new ApiException("limit.unexist", "限额信息不存在");
		}
		//单笔限额
		if(new BigDecimal(params.getAmount()).compareTo(limit.getSingleLimit())==1){//超出单笔限额
			throw new ApiException("single.limit.error", "超出单笔限额，单笔限额"+limit.getSingleLimit());
		}
		//日限额
		BigDecimal dailyAmount = transService.sumDailyAmount(member.getMemberNo());
		BigDecimal caAmunt = dailyAmount.add(new BigDecimal(params.getAmount()));
		if(caAmunt.compareTo(limit.getDailyLimit())==1){
			throw new ApiException("daily.limit.error", "超出日限额，日限额"+limit.getDailyLimit());
		}
		//创建支付流水
		MchReg reg = mchRegService.findByMchNo(member.getMemberNo());
		if(reg==null){
			throw new ApiException("unreg", "商户尚未认证");
		}
		MchBus bus = mchBusService.findBychMerCode(reg.getChMerCode());
		if(bus==null){
			throw new ApiException("unreg_bus", "商户业务尚未开通");
		}
		//流水创建
		Trans trans = null;
		try {
			trans = createTrans(params.getAmount(),reg,bus);
		} catch (Exception e) {
			throw new ApiException("create_trans_error", "流水创建异常");
		}
		//请求参数封装
		QuickPay requset = new QuickPay();
		requset.setAccNo(card.getCardNo());
		requset.setBusCode("2001");
		requset.setCallBackUrl(JftConfigure.JFTNOTIFYURL);
		requset.setChMerCode(reg.getChMerCode());
		requset.setFrontUrl(JftConfigure.JFTRETURNURL);
		requset.setIdCard(reg.getIdCard());
		requset.setMobile(reg.getMobile());
		requset.setOrderAmount(params.getAmount());
		requset.setOrderCode(trans.getPlatOrderCode());
		requset.setOrderTime(trans.getOrderTime());
		requset.setRealName(reg.getRealName());
		requset.setSettleType("0");
		requset.setVerCode("1001");
		requset.getSettleType();

		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String encryptDate = JsonUtils.mapToJson(ObjectUtils.Obj2Map(requset));
			byte[] encrypt = AESUtil.encryptAES(encryptDate.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			dataMap.put("orgCode", JftConfigure.ORG_CODE);
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			String linkString = MD5Utils.createLinkString(ObjectUtils.Obj2Map(requset)); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/quickPay", dataMap);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApiException("unexception", "请求渠道未知异常");
		}
		logger.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException("unexception", "渠道返回数据异常");
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resCode = jsonObject.getString("resCode");
			String resMsg = jsonObject.getString("resMsg");
			transService.update(trans.getId(),2,resCode,resMsg);
			logger.info("渠道响应：resCode={}|resMsg={}",resCode,resMsg);
			throw new ApiException("response.error","渠道返回错误");
		}
		String encryptData = jsonObject.getString("encryptData");
		JSONObject resObject = null;
		try {
			byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (Exception e) {
			throw new ApiException("unexception", "未知异常");
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		String resMsg = resObject.getString("resMsg");
		String resultType = resObject.getString("resultType");
		String url = "";
		if("0000".equals(resCode)){
			if("url_address".equals(resultType)){
				url = resObject.getString("url");
			}else if("html_text".equals(resultType)){
				url = resObject.getString("html");
			}
		}else{
			transService.update(trans.getId(),2,resCode,resMsg);
			throw new ApiException(resCode,resMsg);
		}
		Map<String,String> resutltMap = new HashMap<String,String>();
		resutltMap.put("url", url);
		resutltMap.put("orderCode", trans.getPlatOrderCode());
		return new AjaxRes(AjaxRes.SUCCESS, "请求成功",url);
	}

	private Trans createTrans(String amount, MchReg reg, MchBus bus) {
		Trans trans = new Trans();
		BigDecimal orerAmount = new BigDecimal(amount);
		BigDecimal tradeFee = orerAmount.multiply(bus.getTradeRate());
		BigDecimal actualAmount = orerAmount.subtract(tradeFee).subtract(bus.getDrawFee());
		trans.setAccNo(reg.getAccountNo());
		trans.setBusCode("2001");
		trans.setCallBackUrl("");
		trans.setFrontUrl("");
		trans.setChMerCode(reg.getChMerCode());
		trans.setCreateTime(new Date());
		trans.setIdCard(reg.getIdCard());
		trans.setMchName(reg.getAccountName());
		trans.setMchNo(reg.getMchNo());
		trans.setMerCode(reg.getMerCode());
		trans.setMobile(reg.getMobile());
		trans.setOrderAmount(new BigDecimal(amount));
		trans.setTradeRate(bus.getTradeRate());
		trans.setDrawFee(bus.getDrawFee());
		trans.setTradeFee(tradeFee);
		trans.setActualAmount(actualAmount);
		trans.setOrderCode(DateUtil.getAllTime());
		trans.setPlatOrderCode(idWorkerService.idGenerator());
		trans.setOrderTime(DateUtil.getAllTime());
		trans.setRealName(reg.getRealName());
		trans.setSettleType(0);//D0
		trans.setTranStatus(1);//交易中
		transService.insert(trans);
		return trans;
	}
	

	@Override
	public AjaxRes memberReg(ApiMchRegParams params) {
		Result ret = FluentValidator.checkAll()
				.on(params, new HibernateSupportedValidator<ApiMchRegParams>().setHiberanteValidator(validator))
				.doValidate().result(toSimple());
		if (!ret.isSuccess()) {
			String msg = ret.getErrors().get(0);
			throw new ApiException("validate.error", msg);
		}
		Member member = memberService.selectById(Integer.parseInt(params.getMemberId()));
		if(member==null){
			throw new ApiException("empty.member", "会员不存在"); 
		}
		//请求参数封装
		String platMerCode = idWorkerService.idGenerator();
		Map<String,String> mchMap = createMchMap(params,platMerCode);
		Map<String,String> dataMap = new HashMap<String,String>();
		dataMap.put("orgCode", JftConfigure.ORG_CODE);
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(mchMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(mchMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/memberReg", dataMap);
		} catch (Exception e2) {
			e2.printStackTrace();
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		logger.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException("channel.unkonw.exception","未知异常");
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resCode = jsonObject.getString("resCode");
			String resMsg = jsonObject.getString("resMsg");
			logger.info("渠道响应：resCode={}|resMsg={}",resCode,resMsg);
			throw new ApiException(resCode,resMsg);
		}
		JSONObject resObject = null;
		String encryptData = jsonObject.getString("encryptData");
		try {
			byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		String resMsg = resObject.getString("resMsg");
		String chMerCode = "";
		String merCode = DateUtil.getAllTime();
		if("0000".equals(resCode)){
			chMerCode = resObject.getString("chMerCode");
			createMchReg(params,chMerCode,platMerCode,member.getMemberNo(),merCode);
		}else{
			return new AjaxRes(resCode, resMsg);
		}
		boolean flag = memberBus(chMerCode,merCode);
		if(!flag){
			return new AjaxRes("openbus.error", "业务开通失败"); 
		}
		//会员认证状态更新
		member.setAuthStatus(2);//认证通过
		member.setAuthTime(new Date());
		memberService.updateById(member);
		
		return new AjaxRes(AjaxRes.SUCCESS, "注册成功");
	}
	
	private MchReg createMchReg(ApiMchRegParams req, String chMerCode,String platMerCode,String memberNo,String merCode) {
		MchReg reg = new MchReg();
		reg.setResCode("0000");
		reg.setResMsg("认证成功");
		reg.setMchNo(memberNo);
		reg.setAccountName(req.getRealName());
		reg.setChMerCode(chMerCode);
		reg.setAccountNo(req.getAccountNo());
		reg.setBankCode(req.getBankCode().split("-")[0]);	
		reg.setBankName(req.getBankCode().split("-")[1]);
		reg.setSubBankCode(req.getBankCode());
//		reg.setCityCode(req.getCityCode());
		reg.setIdCard(req.getIdCard());
//		reg.setMerAddress(req.getMerAddress());
		reg.setMerCode(merCode);
		reg.setPlatMerCode(platMerCode);
		reg.setMerName(req.getMerName());
		reg.setMobile(req.getMobile());
//		reg.setOpenCity(req.getOpenCity());
//		reg.setOpenProvince(req.getOpenProvince());
//		reg.setProvinceCode(req.getProvinceCode());
		reg.setRealName(req.getRealName());
		reg.setReservedMobile(req.getMobile());
		reg.setSubBankCode(req.getSubBankCode());	
		reg.setStatus(1);//成功
		reg.setCreateTime(new Date());
		mchRegService.insert(reg);
		return reg;
	}

	
	private Map<String, String> createMchMap(ApiMchRegParams req,String platMerCode) {
		Map<String,String> mchMap = new HashMap<String,String>();
		mchMap.put("verCode", "1001");
		mchMap.put("merCode", platMerCode);
		mchMap.put("merName", req.getMerName());
		mchMap.put("realName", req.getRealName());
		mchMap.put("idCard", req.getIdCard());
		mchMap.put("mobile", req.getMobile());
		mchMap.put("accountName", req.getRealName());
		mchMap.put("accountNo", req.getAccountNo());
		mchMap.put("reservedMobile", req.getMobile());
		if(!Strings.isNullOrEmpty(req.getBankCode())){
			mchMap.put("bankCode", req.getBankCode().split("-")[0]);
			mchMap.put("bankName", req.getBankCode().split("-")[1]);
		}
		mchMap.put("subBankCode", req.getSubBankCode());
		return mchMap;
	}

	private boolean memberBus(String chMerCode,String merCode) {
		//请求渠道
		Map<String,String> reqMap = new HashMap<String,String>();
		reqMap.put("verCode", "1001");
		reqMap.put("chMerCode", chMerCode);
		reqMap.put("busCode", "2001");
		reqMap.put("drawFee", JftConfigure.DRAWFEE);
		reqMap.put("tradeRate", JftConfigure.TRADERATE);
		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(reqMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(reqMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("orgCode", JftConfigure.ORG_CODE);
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/memberBus", dataMap);
		} catch (Exception e2) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException(ResultEnum.CHANNEL_RESPONSE_ERROR);
		}
		logger.info("resStr="+resStr);//{"resCode":"0015","resMsg":"签名错误"}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resMsg = jsonObject.getString("resMsg");
			throw new ApiException("busopen.error",resMsg);
		}
		JSONObject resObject = null;
		String encryptData = jsonObject.getString("encryptData");
		try {
			byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (Exception e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		String resMsg = resObject.getString("resMsg");
		if("0000".equals(resCode)){
			MchBus bus = new MchBus();
			bus.setBusCode("2001");
			bus.setChMerCode(chMerCode);
			bus.setDrawFee(new BigDecimal(JftConfigure.DRAWFEE));
			bus.setMerCode(merCode);
			bus.setTradeRate(new BigDecimal(JftConfigure.TRADERATE));
			bus.setStatus(1);
			bus.setResCode(resCode);
			bus.setResMsg(resMsg);
			mchBusService.insert(bus);
		}else{
			return false;
		}
		return true;
	}

	@Override
	public Object rateModify(Map<String, String> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object bankCardModify(Map<String, String> params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object query(Map<String, String> params) {
		String platOrderCode = params.get("orderCode");
		if(Strings.isNullOrEmpty(platOrderCode)){
			return new AjaxRes("empty.orderCode","订单号为空");
		}
		Trans trans = transService.findByPlatOrderCode(platOrderCode);
		if(trans==null){
			return new AjaxRes("order.unexist","订单为存在");
		}
		//请求参数封装
		Map<String,String> queryMap = new HashMap<String,String>();
		queryMap.put("verCode", "1001");
		queryMap.put("chMerCode", trans.getChMerCode());
		queryMap.put("orderCode", trans.getPlatOrderCode());
		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(queryMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(queryMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			//请求
			dataMap.put("orgCode",JftConfigure.ORG_CODE);
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/tradeQuery", dataMap);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		logger.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException(ResultEnum.CHANNEL_RESPONSE_ERROR);
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			throw new BusException(jsonObject.getString("resCode"), jsonObject.getString("resMsg"));
		}
		String encryptData = jsonObject.getString("encryptData");
		byte[] resDate = null;
		try {
			resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
		} catch (Exception e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		JSONObject resObject = null;
		try {
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		logger.info("resObject="+resObject.toJSONString());
		Map<String,String> resultMap = new HashMap<String,String>();
		String resCode = resObject.getString("resCode");
		Integer tranStatus = resObject.getInteger("tranStatus");
		if("0000".equals(resCode) && trans.getTranStatus()!=tranStatus){
			Trans updateTrans = new Trans();
			updateTrans.setId(trans.getId());
			updateTrans.setTranTime(resObject.getString("tranTime"));
			updateTrans.setTranStatus(resObject.getInteger("tranStatus"));
			updateTrans.setDrawStatus(resObject.getInteger("drawStatus"));
			updateTrans.setDrawAmount(resObject.getBigDecimal("drawAmount"));
			transService.updateById(updateTrans);
			logger.info(trans.getPlatOrderCode()+"订单状态更新"+tranStatus);
		}
		resultMap.put("tranStatus", resObject.getString("tranStatus"));
		resultMap.put("drawStatus", resObject.getString("drawStatus"));
		resultMap.put("tranTime",resObject.getString("tranTime"));
		resultMap.put("orderCode",trans.getPlatOrderCode());
		return new AjaxRes(AjaxRes.SUCCESS,"",resultMap);
	}

	
	@Override
	public AjaxRes regBus(String chMerCode) {
		MchReg reg = mchRegService.findByChMerCode(chMerCode);
		if(reg==null){
			return new AjaxRes("mch.unexist", "商户不存在");
		}
		if(reg!=null && reg.getStatus()==1){
			return new AjaxRes("reged", "已认证");
		}
		Map<String,String> reqMap = new HashMap<String,String>();
		reqMap.put("verCode", "1001");
		reqMap.put("chMerCode", chMerCode);
		reqMap.put("busCode", "2001");
		reqMap.put("drawFee", JftConfigure.DRAWFEE);
		reqMap.put("tradeRate", JftConfigure.TRADERATE);
		Map<String,String> dataMap = new HashMap<String,String>();
		String resStr = "";
		try {
			String linkString = MD5Utils.createLinkString(reqMap); 
			String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
			byte[] encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(reqMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
			dataMap.put("orgCode", JftConfigure.ORG_CODE);
			dataMap.put("signData", sign);
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/memberBus", dataMap);
		} catch (Exception e2) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		if(Strings.isNullOrEmpty(resStr)){
			throw new ApiException(ResultEnum.CHANNEL_RESPONSE_ERROR);
		}
		logger.info("resStr="+resStr);//{"resCode":"0015","resMsg":"签名错误"}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resMsg = jsonObject.getString("resMsg");
			throw new ApiException("busopen.error",resMsg);
		}
		JSONObject resObject = null;
		String encryptData = jsonObject.getString("encryptData");
		try {
			byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (Exception e) {
			throw new ApiException(ResultEnum.UNKONW_EXCEPTION);
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		String resMsg = resObject.getString("resMsg");
		if("0000".equals(resCode)){
			MchBus bus = new MchBus();
			bus.setBusCode("2001");
			bus.setChMerCode(chMerCode);
			bus.setDrawFee(new BigDecimal(JftConfigure.DRAWFEE));
			bus.setMerCode(reg.getMerCode());
			bus.setTradeRate(new BigDecimal(JftConfigure.TRADERATE));
			bus.setStatus(1);
			bus.setResCode(resCode);
			bus.setResMsg(resMsg);
			mchBusService.insert(bus);
		}else{
			return new AjaxRes(resCode, resMsg);
		}
		return new AjaxRes(AjaxRes.SUCCESS, "开通成功");
	}



}
